package cn.comon.app.scan.service.analysis.impl;

import java.util.Iterator;

import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import net.sf.json.JSONException;
import net.sf.json.JSONObject;
import cn.comon.app.scan.component.SysConfigBean;
import cn.comon.app.scan.entity.AsCheckresult;
import cn.comon.app.scan.entity.AsReportinfo;
import cn.comon.app.scan.service.AsCheckresultService;
import cn.comon.app.scan.service.AsReportinfoService;
import cn.comon.app.scan.service.analysis.IAnalysisScanResult;
import cn.comon.app.scan.util.UtilTools;
@Service("netQinAnalysisScanResultImpl")
@Transactional
public class NetQinAnalysisScanResultImpl implements IAnalysisScanResult {
    @Autowired
    private AsReportinfoService asReportinfoServiceImpl;;
    @Autowired
    private AsCheckresultService asCheckresultServiceImpl;
    private static Logger logger = Logger.getLogger(NetQinAnalysisScanResultImpl.class.getName());
    
    private JSONObject saveScanResult(AsCheckresult asCheckresult, AsReportinfo asReportinfo) {
        //检索AsCheckresult表，确认该条记录是否曾经被同一家检测方检测过
        //记录不存在，插入新记录
        //记录存在，更新检测信息
        AsCheckresult asCheckresultTMP =
            asCheckresultServiceImpl.findByRidAndResultIndex(asCheckresult);
        if (asCheckresultTMP == null) {
            asCheckresultServiceImpl.addObj(asCheckresult);
        } else {
            asCheckresultServiceImpl.updateCheckresult(asCheckresult);
        }
        
        asReportinfoServiceImpl.updateReportinfo(asReportinfo);
        return new JSONObject();
    }
    
	public JSONObject checkResult(JSONObject resultData) {
	    try {
	        Document doc = DocumentHelper.parseText(resultData.getString("callback"));
	        String sid = resultData.getString("sid");
	        Element rootElt = doc.getRootElement(); // 获取根节点
	        String appname = "";
	        String platform = "";
	        String filesize = "";
	        String security = "";
	        String virusname = "";
	        String reason = "";
	        Iterator  pkgInfo = rootElt.elementIterator("pkgInfo"); ///获取根节点下的子节
	        // 遍历callback节点
	        while (pkgInfo.hasNext()) {
	          Element recordEless = (Element) pkgInfo.next();
	          appname = recordEless.elementTextTrim("appname"); // 拿到body节点下的子节点result值
	          platform = recordEless.elementTextTrim("platform"); // 拿到body节点下的子节点result值
	          filesize = recordEless.elementTextTrim("filesize"); // 拿到body节点下的子节点result值
	        }
	        Iterator  responseInfo = rootElt.elementIterator("responseInfo"); ///获取根节点下的子节
	        // 遍历callback节点
	        while (responseInfo.hasNext()) {
	          Element recordEless = (Element) responseInfo.next();
	          security = recordEless.elementTextTrim("security"); // 拿到body节点下的子节点result值
	          virusname = recordEless.elementTextTrim("virusname"); // 拿到body节点下的子节点result值
	          reason = recordEless.elementTextTrim("reason"); // 拿到body节点下的子节点result值
	        }
	        
	        //数据接收成功，进行数据库更新。
	        AsCheckresult asCheckresult = new AsCheckresult();
	        //通过返回的sid,检索reportinfo表里对应的记录
	        AsReportinfo asReportinfo = asReportinfoServiceImpl.findByID(sid);
	        asCheckresult.setRid(asReportinfo.getId());
	        asCheckresult.setPackageUrlHash(asReportinfo.getPackageUrlHash());
	        asCheckresult.setResultIndex(4);
//	        int safeType;
	        if ("safe".equals(security)) {
	            asCheckresult.setSafeType(1);
	        } else if ("dangerous".equals(security)){
	            asCheckresult.setSafeType(2);
	        }
	        
	        asCheckresult.setVirusName(UtilTools.convertNnllToString(virusname));
	        asCheckresult.setVirusDesc(UtilTools.convertNnllToString(reason));
	        asCheckresult.setResultDescr("");
	        asCheckresult.setAdinfo("");
//	        asCheckresult.setScore(0);
	        if (!UtilTools.convertNnllToString(filesize).equals("")) {
	            asCheckresult.setSize(Integer.parseInt(filesize));
	        }
	        asCheckresult.setPlatform(platform);
//	        asCheckresult.setOfficial();
	        asCheckresult.setCreateTime(UtilTools.getTimestamp(0));
	        asCheckresult.setLastUpdateTime(UtilTools.getTimestamp(0));

	        //AsReportinfo表更新（checkCount，expired，lastUpdateTime）
	        AsReportinfo asReportinfoTMP = new AsReportinfo();
	        asReportinfoTMP.setId(asReportinfo.getId());
	        //安全基本不确定，过期时间统一延后15天
	        int expired = 0;
	        if ("safe".equals(security)) {
	            //检测结果为安全，但是举报次数又多时，将缩短再次检测时间间隔
	            expired = Integer.parseInt(SysConfigBean.getProperty("result.safetype.safe")); //推后180天再扫描
	        } else if ("dangerous".equals(security)){
	            expired = Integer.parseInt(SysConfigBean.getProperty("result.safetype.dangerous"));
	        }
	        //Expired过期时间，SQL语句中计算更新
	        asReportinfoTMP.setExpired(expired);
	        asReportinfoTMP.setCheckTime(UtilTools.getTimestamp(0));
	        
	        saveScanResult(asCheckresult, asReportinfoTMP);
	        
            logger.info("callback from Netqin,appname=" + appname + ";sid=" + sid);
            logger.info("callback from Netqin,platform=" + platform + ";sid=" +sid);
            logger.info("callback from Netqin,filesize=" + filesize + ";sid=" + sid);
            logger.info("callback from Netqin,security=" + security + ";sid=" + sid);
            logger.info("callback from Netqin,virusname=" + virusname + ";sid=" + sid);
            logger.info("callback from Netqin,reason=" + reason + ";sid=" + sid);
	    } catch (JSONException e) {
            logger.error(e);
        } catch (DocumentException e) {
            logger.error(e);
        }  catch (Exception e) {
            logger.error(e);
        }
        JSONObject result = new JSONObject();
        return result;
	}
}
